package com.cai.activiti_demo1.schedule;

import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.Serializable;
import java.util.List;
import java.util.Objects;

//@Component
@Configuration
@Slf4j
public class DataSchedule {
    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;
    private static Integer ONCE_COUNT;

    @Scheduled(fixedRate = 1000) // 三秒
    public void flushAllBookingData() {
        ValueOperations<String, Serializable> opsForValue = redisTemplate.opsForValue();
        if (Boolean.TRUE.equals(redisTemplate.hasKey("taskKey"))) {
            String value=Objects.requireNonNull(opsForValue.get("taskKey")).toString();
            log.info("taskKey => "+ value);
            completeTask(value);
            redisTemplate.delete("taskKey");
        }
    }

    /**
     * 执行任务
     */
    public void completeTask(String value){
        ProcessEngine processEngine= ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = processEngine.getTaskService();
        List<Task> taskList = taskService.createTaskQuery().taskAssignee(value).list();
        if (taskList.isEmpty()) {
            log.info("当前用户没有待办任务");
            return;
        }
        for (Task task : taskList) {
            taskService.complete(task.getId());
        }
        log.info("待办任务执行完毕");
    }
}
